package com.zt.csp.shorturl.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.zt.csp.shorturl.dto.ServiceResult;
import com.zt.csp.shorturl.entity.ViewLog;
import com.zt.csp.shorturl.service.ShortUrlService;
import com.zt.csp.shorturl.service.ViewLogService;
import com.zt.csp.shorturl.utils.IpQueryer;
import com.zt.csp.shorturl.utils.NetworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 短链接跳转Controller
 * Created by zt on 2018/4/11 0011
 */
@Controller
public class ShortUrlController {
    private static final Logger logger = LoggerFactory.getLogger(ShortUrlController.class);

    @Autowired
    private ViewLogService viewLogService;

    @Autowired
    private ShortUrlService shortUrlService;

    /**
     * 直接跳转，响应类似 r2a.cn/a0001K 这样的请求，短链接最核心的方法。
     *
     * @param shortUrlCode 短链接Code
     * @param response     response响应
     * @return 302跳转
     * @throws IOException
     */
    @GetMapping("/{shortUrlCode}")
    public String redirect(@PathVariable(required = false) String shortUrlCode, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 如果没有传Code，则跳转到首页去
        if (StringUtils.isEmpty(shortUrlCode)) {
            return "index";
        }
        ViewLog viewLog = new ViewLog();
        viewLog.setReqShortCode(shortUrlCode);
        String ipAddress = NetworkUtil.getIpAddress(request);
        viewLog.setReqIp(ipAddress);
        ObjectNode ipInfo = IpQueryer.getIpInfo(ipAddress);
        if (ipInfo != null && ipInfo.get("ret").asInt() == 200) {
            JsonNode data = ipInfo.get("data");
            if (data != null) {
                viewLog.setReqIsp(data.get("isp").asText());
                viewLog.setReqCity(data.get("city").asText());
                viewLog.setReqCityId(data.get("city_id").asText());
                viewLog.setReqRegion(data.get("region").asText());
                viewLog.setReqRegionId(data.get("region_id").asText());
                viewLog.setReqCountry(data.get("country").asText());
                viewLog.setReqCountryId(data.get("country_id").asText());
                viewLog.setReqArea(data.get("area").asText());
            }
        }
        ServiceResult serviceResult = shortUrlService.getLongUrlByShortUrl(shortUrlCode);
        if (serviceResult.getCode() == 200) {
            Map data = (Map) serviceResult.getData();
            logger.info(data.toString());
            viewLog.setReqShortId((Long) data.get("id"));
            viewLog.setReqStatus(0);
            viewLog.setReqMessage("访问正常");
            ServiceResult result = viewLogService.saveLog(viewLog);
            logger.info(result.getMessage());
            response.sendRedirect((String) data.get("longUrl"));
            return null;
        } else {
            // 如果找不到指定短链接Code，则跳转到404页面。
            // todo 这边由于不是商城独有的短链，所以需要自己设计一个404页面。
            viewLog.setReqStatus(2);
            viewLog.setReqMessage("找不到响应的短链接，访问404页面");
            ServiceResult result = viewLogService.saveLog(viewLog);
            logger.info(result.getMessage());
            response.sendRedirect("https://www.zt.com/404.html");
            return null;
        }
    }

}
